package abg.core.service.sys.impl;


import abg.core.common.security.AuthUser;
import abg.core.common.security.AuthKit;
import abg.core.common.util.IdKit;
import abg.core.common.util.StringKit;
import abg.core.common.util.valid.Ids;
import abg.core.common.util.valid.Max;
import abg.core.common.util.valid.Min;
import abg.core.common.util.valid.NotBlank;
import abg.core.common.util.valid.base.Valid;
import abg.core.domain.db.SysMsg;
import abg.core.domain.db.SysMsgRead;
import abg.core.domain.search.Psh;
import abg.core.mapper.SysMsgMapper;
import abg.core.mapper.SysMsgReadMapper;
import abg.core.service.sys.SysMsgService;
import abg.core.service.sys.SysMsgTypeService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static abg.core.domain.db.table.SysMsgReadTableDef.SYS_MSG_READ;
import static abg.core.domain.db.table.SysMsgTableDef.SYS_MSG;

/**
 * 系统消息
 */
@Slf4j
@Service
public class SysMsgServiceImpl implements SysMsgService {
    @Resource
    private SysMsgMapper msgMapper;

    @Resource
    private SysMsgReadMapper msgReadMapper;

    @Resource
    private SysMsgTypeService msgTypeService;

    //剩余未读消息
    @Override
    public long notReadMsgCount() {
        AuthUser authUser = AuthKit.mastLogin();
        String userId = authUser.getUserId();
        QueryWrapper wrapper = QueryWrapper.create()
                .eq("read_user_id", userId)
                .eq("is_read", "0");
        return msgReadMapper.selectCountByQuery(wrapper);
    }

    //前几条未读消息
    @Override
    public List<SysMsg> msgTopList(String type, @Max(10) @Min(1) int size) {
        AuthUser authUser = AuthKit.mastLogin();

        String userId = authUser.getUserId();

        QueryWrapper wrapper = QueryWrapper.create()
                .select("msg_id")
                .eq("read_user_id", userId)
                .eq("is_read", "0")
                .orderBy(SYS_MSG_READ.CT.desc())
                .limit(size);

        List<String> mgsIds = msgReadMapper.selectObjectListByQueryAs(wrapper, String.class);

        if (mgsIds.size() == 0) return new ArrayList<>();

        return msgMapper.selectListByIds(mgsIds);
    }

    //消息主体
    @Override
    public Page<SysMsg> msgPageData(SysMsg param, Psh psh) {
        QueryWrapper wrapper = QueryWrapper.create()
                .and(SYS_MSG.MSG_TYPE_ID.eq(param.getMsgTypeId()))
                .and(SYS_MSG.TITLE.like(param.getTitle()))
                .orderBy(SYS_MSG.CT.desc());
        Page paginate = msgMapper.paginate(psh, wrapper);

        return paginate;
    }

    //我的消息
    @Override
    public Page<Object> userPageData(SysMsg param, Psh psh) {
        AuthUser authUser = AuthKit.mastLogin();
        String userId = authUser.getUserId();

        //查未读消息ID
        QueryWrapper wrapper = QueryWrapper.create()
                .select("msg_id,is_read")
                .eq("read_user_id", userId)
                .orderBy(SYS_MSG_READ.CT.desc(), SYS_MSG_READ.ID.desc());
        Page paginate = msgReadMapper.paginate(psh, wrapper);

        List<SysMsgRead> msgReadList = paginate.getRecords();

        if (msgReadList.size() != 0) {

            ArrayList<Object> sysMsgList = new ArrayList<>(msgReadList.size());

            for (SysMsgRead sysMsgRead : msgReadList) {
                SysMsg sysMsg = msgMapper.selectOneById(sysMsgRead.getMsgId());
                sysMsg.setMsgTypeName(msgTypeService.getNameById(sysMsg.getMsgTypeId()));
                sysMsg.setIsRead(sysMsgRead.getIsRead());
                sysMsgList.add(sysMsg);
            }

            paginate.setRecords(sysMsgList);

        }

        return paginate;
    }

    @Valid
    @Override
    public SysMsg info(@NotBlank String id) {
        return msgMapper.selectOneById(id);
    }

    @Valid
    @Override
    public boolean delete(@Ids String ids) {
// msgMapper.deleteBatchByIds(StringKit.split(ids));
//
        AuthUser authUser = AuthKit.mastLogin();

        QueryWrapper and = QueryWrapper.create()
                .and(SYS_MSG_READ.MSG_ID.in(StringKit.split(ids)))
                .and(SYS_MSG_READ.READ_USER_ID.eq(authUser.getUserId()));

        msgReadMapper.deleteByQuery(and);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(SysMsg param) {
        //插入消息主体
        param.setId(IdKit.getId());
        msgMapper.insertSelective(param);

        //通知用户
        ArrayList<String> userIds = param.getSendToUserIds();
        ArrayList<SysMsgRead> objects = new ArrayList<>(userIds.size());
        for (String userId : userIds) {
            SysMsgRead sysMsgRead = new SysMsgRead();
            sysMsgRead.setMsgId(param.getId());
            sysMsgRead.setReadUserId(userId);
            sysMsgRead.setIsRead("0");
            sysMsgRead.setReadTime(null);
            objects.add(sysMsgRead);
        }
        msgReadMapper.insertBatch(objects, 200);

        return true;
    }

    @Override
    public boolean readAll() {
        AuthUser authUser = AuthKit.mastLogin();
        QueryWrapper and = QueryWrapper.create().and(SYS_MSG_READ.READ_USER_ID.eq(authUser.getUserId()));
        SysMsgRead sysMsgRead = new SysMsgRead();
        sysMsgRead.setIsRead("1");
        msgReadMapper.updateByQuery(sysMsgRead, and);
        return true;
    }

    @Valid
    @Override
    public boolean readBatch(@Ids String msgIds) {
        AuthUser authUser = AuthKit.mastLogin();
        ArrayList<String> split = StringKit.split(msgIds);
        QueryWrapper and = QueryWrapper.create()
                .and(SYS_MSG_READ.MSG_ID.in(split))
                .and(SYS_MSG_READ.READ_USER_ID.eq(authUser.getUserId()));
        SysMsgRead sysMsgRead = new SysMsgRead();
        sysMsgRead.setIsRead("1");
        msgReadMapper.updateByQuery(sysMsgRead, and);
        return true;
    }

}
